package com.yiwyn;

import java.io.IOException;
import java.lang.instrument.ClassFileTransformer;
import java.lang.instrument.IllegalClassFormatException;
import java.lang.instrument.Instrumentation;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.security.ProtectionDomain;

public class JavaAgentDemo {


    public static void premain(String agentArgs, Instrumentation inst) {
        System.out.println("hello java agent");


        inst.addTransformer(new ClassFileTransformer() {
            @Override
            public byte[] transform(ClassLoader loader, String className, Class<?> classBeingRedefined, ProtectionDomain protectionDomain, byte[] classfileBuffer) throws IllegalClassFormatException {

                if (!className.equals("com/yiwyn/service/TestService")) {
                    return null;
                }

                String filePath = "/Users/yiwyn/IdeaProjects/spring-demo/java-agent-demo/jar/TestService.class";
                try {
                    return Files.readAllBytes(Paths.get(filePath));
                } catch (IOException e) {
                    throw new RuntimeException(e);
                }
            }
        }, true);


    }

}
